package com.zhida.smartcontrol.pagectrl.projectdetail.zonemanager.adddevice;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.jay.tools.base.BaseDialogFragment;
import com.jay.tools.recycler.OnItemClick;
import com.jay.tools.ui.ButtonStyle;
import com.jay.tools.ui.TopBarView;
import com.jay.tools.utils.EventBusUtils;
import com.jay.tools.utils.ResUtil;
import com.jay.tools.utils.SoftInputUtils;
import com.tan.fonticon.widget.IconTextView;
import com.tan.linkpicker.pickerview.builder.OptionsPickerBuilder;
import com.tan.linkpicker.pickerview.listener.CustomListener;
import com.tan.linkpicker.pickerview.listener.OnOptionsSelectListener;
import com.tan.linkpicker.pickerview.view.OptionsPickerView;
import com.zhida.smartcontrol.R;
import com.zhida.smartcontrol.common.Api;
import com.zhida.smartcontrol.common.Const;
import com.zhida.smartcontrol.common.PhotoDialogFragment;
import com.zhida.smartcontrol.common.PhotoOkEvent;
import com.zhida.smartcontrol.common.bean.DeviceClassifyBean;
import com.zhida.smartcontrol.common.bean.LampBean;
import com.zhida.smartcontrol.common.mapsel.MapSelFragment;
import com.zhida.smartcontrol.dialog.OkDialogFragment;
import com.zhida.smartcontrol.dialog.devicelistdialog.DeviceListDialogFragment;
import com.zhida.smartcontrol.dialog.grouplistdialog.GroupListDialogFragment;
import com.zhida.smartcontrol.mvp.MVPBaseFragment;
import com.zhida.smartcontrol.pagectrl.ProjectListBean;
import com.zhida.smartcontrol.pagectrl.projectdetail.GroupBean;
import com.zhida.smartcontrol.pagehome.scan.ScanFragment;
import com.zhida.smartcontrol.pagehome.scan.ScanResultEvent;
import com.zhida.smartcontrol.pop.DeviceClassifyPop;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * author: tanjianpei
 * date: 2019/10/21 021 10:30
 * description: 添加或编辑集控器
 */
@SuppressLint("SetTextI18n")
public class AddDeviceFragment extends MVPBaseFragment<AddDeviceContract.View, AddDevicePresenter> implements AddDeviceContract.View {
    @BindView(R.id.top)
    TopBarView mTopBar;
    @BindView(R.id.tv_sel_location)
    TextView mTvLocation; // 此功能本版本不做
    @BindView(R.id.tv_project_name)
    TextView mTvProjectName;
    @BindView(R.id.tv_group_name)
    TextView mTvGroupName;
    @BindView(R.id.et_device_name)
    EditText mEtDeviceName;
    @BindView(R.id.et_imei)
    EditText mEtImei;
    @BindView(R.id.et_device_num)
    EditText mEtDeviceNum;
    @BindView(R.id.et_card)
    EditText mEtCard;
    @BindView(R.id.et_factory)
    EditText mEtFactory;
    @BindView(R.id.et_lng)
    EditText mEtLng; //经度
    @BindView(R.id.et_lat)
    EditText mEtLat; // 纬度
    @BindView(R.id.et_address)
    EditText mEtAddress;
    @BindView(R.id.iv_pic)
    ImageView mIvPic;
    @BindView(R.id.btn_save)
    ButtonStyle mBtnSave;
    @BindView(R.id.tv_switch_type)
    TextView mTvSwitchType;
    @BindView(R.id.et_num)
    EditText mEtNum;
    @BindView(R.id.tv_project_name1)
    TextView mTvProjectName1;
    @BindView(R.id.tv_qu_duan)
    TextView mTvQuduan;

    private int mType;
    private String mId;
    private String mGroupId;
    private String mLat, mLng;
    private String mSwitchType;
    private DeviceClassifyPop mPop;
    private String mFilePath;
    private boolean mLoadOk;
    private String mPicUrl;

    private int mClickType;

    private LampBean mBean;
    private OptionsPickerView pvOptions;

    public static AddDeviceFragment newInstance(int type, LampBean bean) {
        Bundle args = new Bundle();
        args.putInt("type", type);
        args.putParcelable("bean", bean);
        AddDeviceFragment fragment = new AddDeviceFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected Object getLayout() {
        return R.layout.fragment_edit_device;
    }

    @Override
    protected void initLazy(Bundle savedInstanceState) {
        inflateTopBar(mTopBar);

        Bundle bundle = getArguments();
        if (null == bundle) {
            return;
        }
        mBean = bundle.getParcelable("bean");
        if (null != mBean) {
            mId = mBean.getId();
            mGroupId = mBean.getGroupId();
            mTvProjectName.setText("所属项目：" + mBean.getProjectName());
            mTvGroupName.setText("所属区段：" + mBean.getGroupName());
        }

        mType = bundle.getInt("type");
        if (mType == Const.TYPE_EDIT) {
            fillEdit(mBean);
            mBtnSave.setText("修改");
            mTopBar.setTitle("编辑集控器");
        } else {
            mBtnSave.setText("保存");
            mTopBar.setTitle("添加集控器");
        }
        mPop = new DeviceClassifyPop(getProxyActivity(), Const.O_CTRL);
        EventBusUtils.register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtils.unregister(this);
    }

    private void fillEdit(LampBean bean) {
        if (null == bean) {
            return;
        }
        mEtDeviceName.setText(bean.getName());
        mEtImei.setText(bean.getImei());
        mEtDeviceNum.setText(bean.getIccid());
        mEtCard.setText(bean.getEquipmentCode());
        mEtNum.setText(bean.getNum() + "");
        mEtFactory.setText(bean.getManufacturer());
        mEtAddress.setText(bean.getAddress());
        mLat = bean.getLat();
        mLng = bean.getLng();
        mEtLat.setText(mLat);
        mEtLng.setText(mLng);
        mSwitchType = bean.getSwitchType();
        mTvSwitchType.setText(bean.getSwitchTypeTxt());

        mPicUrl = bean.getDevicePic();
        loadPic();
    }

    private void loadPic() {
        if (!TextUtils.isEmpty(mPicUrl))
            Glide.with(getProxyActivity())
                    .load(Api.PIC + mPicUrl)
                    .apply(new RequestOptions()
                            .placeholder(R.drawable.progress_round)
                            .error(R.drawable.ic_photo))
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            mLoadOk = false;
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            mLoadOk = true;
                            return false;
                        }
                    })
                    .into(mIvPic);
    }

    @Override
    protected void initLazyEvents() {
        mPop.setClickListener(new OnItemClick<Object>() {
            @Override
            public void onClick(Object info, int tag) {
                DeviceClassifyBean bean = (DeviceClassifyBean) info;
                mSwitchType = bean.getId();
                mTvSwitchType.setText(bean.getName());
            }
        });

    }

    @OnClick({R.id.tv_sel_location, R.id.ll_device_type, R.id.ll_jwd, R.id.btn_save,
            R.id.btn_reset, R.id.tv_take, R.id.iv_pic, R.id.fl_sao_1, R.id.fl_sao_2,R.id.tv_project_name1,R.id.tv_qu_duan})
    public void click(View v) {
        SoftInputUtils.hideSoftInput(getProxyActivity());
        switch (v.getId()) {
            case R.id.tv_sel_location:
                mPresenter.initJsonData();
                break;
            case R.id.ll_jwd:
                requestLocation();
                break;
            case R.id.ll_device_type: //选择类别
                mPop.showAsDropDown(mTvSwitchType, 0, 0);
                break;
            case R.id.iv_pic:
                if (mLoadOk) {

                } else {
                    loadPic();
                }
                break;
            case R.id.tv_take:
                mClickType = 1;
                requestCameraPermission();
                break;
            case R.id.fl_sao_1:
            case R.id.fl_sao_2:
                mClickType = 2;
                requestCameraPermission();
                break;
            case R.id.btn_save:
                String address = mEtAddress.getText().toString().trim();
                String equipmentCode = mEtDeviceNum.getText().toString().trim();
                String imei = mEtImei.getText().toString().trim();
                String manufacturer = mEtFactory.getText().toString().trim();
                String name = mEtDeviceName.getText().toString().trim();
                String num = mEtCard.getText().toString().trim();
                mPresenter.check(mType, address, equipmentCode, mGroupId, imei, mLat, mLng,
                        manufacturer, name, num, mSwitchType, mFilePath, mId, mGroupBean.getId(), mProjectBean.getId());
                break;
            case R.id.btn_reset:
                resetInput();
                break;
            case R.id.tv_project_name1:
                showDialog(DeviceListDialogFragment.newInstance(), 1);
                break;
            case R.id.tv_qu_duan:
                if (null == mProjectBean || TextUtils.isEmpty(mProjectBean.getId())) {
                    showMsg("请选择项目");
                    return;
                }
                showDialog(GroupListDialogFragment.newInstance(mProjectBean.getId()), 2);
                break;
        }
    }
    private ProjectListBean mProjectBean;
    private GroupBean mGroupBean;
    private void showDialog(BaseDialogFragment fragment, int type) {
        fragment.setOnDestroyListener(new BaseDialogFragment.OnDestroyListener() {
            @Override
            public void onDestroy(Object object, boolean isChange) {
                if (null == object) {
                    return;
                }
                switch (type) {
                    case 1:
                        mProjectBean = (ProjectListBean) object;
                        mTvProjectName1.setText(mProjectBean.getProjectName());
                        break;
                    case 2:
                        mGroupBean = (GroupBean) object;
                        mTvQuduan.setText(mGroupBean.getName());
                        break;
                }
            }
        });
        fragment.showDialog(getChildFragmentManager());
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void scanResult(ScanResultEvent event) {
        mEtImei.setText(event.getImei());
        mEtDeviceNum.setText(event.getCardNo());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void photoOk(PhotoOkEvent event) {
        mFilePath = event.getPath();
        Glide.with(getProxyActivity())
                .load(mFilePath)
                .apply(new RequestOptions()
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE))
                .into(mIvPic);
        mLoadOk = true;
    }

    @Override
    protected void openCamera() {
        if (mClickType == 1) {
            PhotoDialogFragment.newInstance().showDialog(getChildFragmentManager());
        } else {
            start(ScanFragment.newInstance(true));
        }
    }

    private void resetInput() {
        if (mType == Const.TYPE_EDIT) {
            fillEdit(mBean);
        } else {
            mEtDeviceName.setText("");
            mEtImei.setText("");
            mEtDeviceNum.setText("");
            mEtCard.setText("");
            mEtFactory.setText("");
            mEtAddress.setText("");
            mLat = "";
            mLng = "";
            mEtLat.setText(mLat);
            mEtLng.setText(mLng);
            mSwitchType = "";
            mTvSwitchType.setText("");
        }
    }

    @Override
    protected void location(boolean hasLocation) {
        startForResult(MapSelFragment.newInstance(), 0);
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == 0 && null != data) {
            mLat = data.getString("lat");
            mLng = data.getString("lng");
            mEtLat.setText(mLat);
            mEtLng.setText(mLng);
        }
    }

    @Override
    public void onSuccess(String msg) {
        OkDialogFragment fragment = OkDialogFragment.newInstance(msg);
        fragment.showDialog(getChildFragmentManager());
        fragment.setOnDestroyListener(new BaseDialogFragment.OnDestroyListener() {
            @Override
            public void onDestroy(Object object, boolean isChange) {
                EventBusUtils.post(new LampBean());
                pop();
            }
        });
    }

    @Override
    public void showJsonData(List<JsonBean> provinceList, List<List<String>> pCityList, List<List<List<String>>> areaList) {
        pvOptions = new OptionsPickerBuilder(getProxyActivity(), new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String opt1tx = provinceList.size() > 0 ?
                        provinceList.get(options1).getPickerViewText() : "";

                String opt2tx = pCityList.size() > 0
                        && pCityList.get(options1).size() > 0 ?
                        pCityList.get(options1).get(options2) : "";

                String opt3tx = pCityList.size() > 0
                        && areaList.get(options1).size() > 0
                        && areaList.get(options1).get(options2).size() > 0 ?
                        areaList.get(options1).get(options2).get(options3) : "";

                String tx = opt1tx + opt2tx + opt3tx;
                mTvLocation.setText(tx);
            }
        })
                .setLayoutRes(R.layout.layout_area_picker, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final ButtonStyle btnSubmit = v.findViewById(R.id.btn_confirm);
                        final ButtonStyle btnCancel = v.findViewById(R.id.btn_cancel);

                        btnSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvOptions.returnData();
                                pvOptions.dismiss();
                            }
                        });
                        btnCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvOptions.dismiss();
                            }
                        });
                    }
                })
                .setDividerColor(ResUtil.getColor(getProxyActivity(), R.color.c_999999))
                .setTextColorCenter(ResUtil.getColor(getProxyActivity(), R.color.c_333333))
                .setContentTextSize(13)
                .setLineSpacingMultiplier(3.0f)
                .build();

        pvOptions.setPicker(provinceList, pCityList, areaList);//三级选择器
        pvOptions.show();
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        stateBar(true);
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        stateBar(false);
    }


}
